package com.nowcoder.community.controller;

import com.nowcoder.community.entity.DiscussPost;
import com.nowcoder.community.entity.Page;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.service.DiscussPostService;
import com.nowcoder.community.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: caoxinfang
 * @email: 2717176337@qq.com
 * @date: 2022/3/8 17:20
 */

@Controller
public class HomeController {

    @Autowired
    private DiscussPostService discussPostService;

    @Autowired
    private UserService userService;

    @RequestMapping(path = "/index", method = RequestMethod.GET)
    public String getIndexPage(Model model, Page page){

        // 方法调用前，SpringMvc会自动实例化Model和Page，并将Page注入Model
        // 所以，在thymeleaf中就直接可以访问Page中的数据
        page.setRows(discussPostService.findDiscussPostRows(0));
        page.setPath("/index");

        // 根据条件查询帖子
        List<DiscussPost> list = discussPostService.findDiscussPosts(0,0,10);
        // 创建一个集合存放拼接username和帖子
        List<Map<String,Object>> discussPosts = new ArrayList<>();
        if (list != null) {
            for (DiscussPost post : list){
                HashMap<String, Object> map = new HashMap<>();
                // 存到集合中
                map.put("post",post);
                // 获取User对象
                User user = userService.findUserById(post.getUserId());
                map.put("user",user);
                discussPosts.add(map);
            }
        }
        model.addAttribute("discussPosts",discussPosts);
        return "/index";
        
        
    }



}
